package com.demo.activityservicedemo.take

import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.demo.activityservicedemo.R
import java.util.concurrent.LinkedBlockingQueue

/**
 * Created by zhangyuncai on 2024/6/26.
 * 无限循环中，用take是一个非常好的做法，当有消息时，线程被唤醒，当无消息时，线程被休眠
 */
class TakeActivity : AppCompatActivity() {

    companion object {
        @Volatile
        private var messageQueue = LinkedBlockingQueue<String>()
    }

    private val tv_take_content by lazy {
        findViewById<TextView>(R.id.tv_take_content)
    }

    private var count = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_take)

        thread.start()
    }

    fun clickAddMessage(view: View) {
        messageQueue.put("消息${count++}")
    }

    val thread = object : Thread() {
        override fun run() {
            while (true) {
                val message = messageQueue.take()
                runOnUiThread {
                    tv_take_content.text=message
                }
                Log.e("test", "message:${message}")
                SystemClock.sleep(1000)
            }
        }
    }
}